package org.jeecg.modules.common.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.common.service.MqttService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Classname CamelliaPLCController
 * @Description TODO
 * @Date 2023/5/28 16:27
 * @Created by 10835
 */
@Api(tags="PLC控制接口")
@RequestMapping("common/plc/")
@RestController
public class CamelliaPLCController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MqttService mqttService;

    @ApiOperation(value="PLC-设备运行状态查询", notes="PLC-设备运行状态查询")
    @GetMapping("camellia_status")
    public Result<Boolean> getCamelliaDeviceStatus(){
        Result<Boolean> result = Result.OK(false);
        String s = stringRedisTemplate.opsForValue().get("CAMELLIA:CAMELLIA_DEVICE_STATUS");
        if (StringUtils.isEmpty(s)) {
             return result;
        }
        int state = Integer.parseInt(s);
        if (state != 1) {
            return result;
        }
        return Result.OK(true);
    }

    @ApiOperation(value="PLC-下发参数", notes="PLC-下发参数")
    @PostMapping("camellia_status")
    public Result<Boolean> syncCamelliaDevicePLCParameter(@RequestBody Map<String,Short> paramsMap){
        String s = stringRedisTemplate.opsForValue().get("CAMELLIA:CAMELLIA_DEVICE_STATUS");
        if (StringUtils.isEmpty(s)) {
            return Result.error("未查询到设备状态，请稍后再试！");
        }
        int state = Integer.parseInt(s);
        if (state == 1) {
            return Result.error("设备正在运行中，请稍后再试！");
        }
        mqttService.sendMessage("/camellia_01/sys/set", JSON.toJSONString(paramsMap),0);
        return Result.ok(true);
    }


}
